## Functions for Replication of
##
## Moore, Ryan T., Eleanor Neff Powell, and Andrew Reeves. "Driving Support:
## Workers, PACs, and Congressional Support of the Auto Industry". Business and
## Politics, 15(2):137-162, 2013.
##
## 1 September 2013

## regressBillsAFL() creates and stores tables of coefficients.  

regressBillsAFL <- function(rc.vec, vote.data = adat, exclude.cells = 1, lopsided = .7, include.factory = TRUE, tables = FALSE, dir = NULL){
  
  storage <- data.frame(vote = NA, intercept = NA, factory = NA, dwnom = NA, lBig3 = NA, lAFL = NA)
  
  if(is.null(dir) & tables == TRUE){
    dir <- "/figs/tabs/"
  }
  ## Note: user-specified dir arguments should end in "/".
  
  for(i in 1:length(rc.vec)){
    
    if((i %% 100) == 0){
      cat(paste("Start roll call ", i, " of ", length(rc.vec), "\n", sep=""))
    }
    rc.tmp <- rc.vec[i]
    
    ## don't operate on unanimous, party votes, or :
    tab <- table(vote.data[, rc.tmp], vote.data[, "party"])
    if(nrow(tab) == 2){
      if(ncol(tab) == 2){
        prop.for <- mean(c(rep(0, (tab[,1]+tab[,2])[1]), rep(1, (tab[,1]+tab[,2])[2])))
      }else{
        prop.for <- mean(c(rep(0, tab[1,1]), rep(1, tab[2,1])))
      }
      
      if((nrow(tab) > 1) & (sum(tab < exclude.cells) < 2) &  ((1-lopsided) < prop.for) & (prop.for < lopsided)){
        #    if((nrow(tab) > 1) & (sum(diag(tab)) != 0) & (sum(diag(tab)) != sum(tab)) & (sum(tab < 1) < 2)){
        ## this is session-specific:
        factory.string <- "factory.s1"
        if(substring(rc.tmp, 12, 12) == 2){
          factory.string <- "factory.s2"
        }
        
        if(tables == TRUE){
          captt <- paste("Logistic Regression Coefficients of Support for House Roll Call ", substr(rc.tmp, start=14, stop=nchar(rc.tmp)), ", Congressional Session ", substr(rc.tmp, start=8, stop=12), ".", sep = "")
          
          if(rc.tmp=="vote.rc110.2.690"){
            captt <- paste(captt, "  Vote on 10 December 2008 for using TARP for auto bailout. Passed 237-170: Democrats 205-20, Republicans 32-150.", sep = "")
          }
          if(rc.tmp=="vote.rc111.1.314"){
            captt <- paste(captt, "  Vote on 9 June 2009 (``Cash for Clunkers''). Passed 298-119: Democrats 239-9, Republicans 59-110.", sep = "")
          }          
            
          reg.table.note <- function(env){
            note <- paste("Table created with R package {\\tt apsrtable}")
            return(note)
          }
          
          s1 <- glm(formula(paste(rc.tmp, " ~ ", factory.string, " + I(as.factor(party))", sep = "")), family = binomial(link = "logit"), data = vote.data)
          s2 <- glm(formula(paste(rc.tmp, " ~ ", factory.string, " + dwnom1", sep = "")), family = binomial(link = "logit"), data = vote.data)
          s3 <- glm(formula(paste(rc.tmp, " ~ ", factory.string, " + I(as.factor(party)) + I(log(Total.Ford + Total.DaimlerChrysler+ Total.GM+1)) +  I(log(Total.AFL.CIO + 1))", sep = "")), family = binomial(link = "logit"), data = vote.data)
          s4 <- glm(formula(paste(rc.tmp, " ~ ", factory.string, " + dwnom1 + I(log(Total.Ford + Total.DaimlerChrysler+ Total.GM+1)) + I(log(Total.AFL.CIO + 1))", sep = "")), family = binomial(link = "logit"), data = vote.data)
          
          out.tab <- apsrtable(s1, s2, s3, s4, coef.names = c("Intercept", "$\\geq$ 1000 auto workers", "Republican", 
                                                              "DW-NOMINATE", "Ford/Chrysler/GM PAC Contribs (log)", "AFL-CIO PAC Contribs (log)"),
                               caption.position = "below", label = paste("t:logit", rc.tmp, sep = ""), caption = captt, notes = list(se.note, stars.note, reg.table.note), stars = "default")
          
          writeLines(out.tab, con = paste(dir, rc.tmp, ".tex", sep = ""))
        }
        
        fmla <- formula(paste(rc.tmp, " ~ ", factory.string, " + dwnom1 + I(log(Total.Ford + Total.DaimlerChrysler+ Total.GM+1)) + I(log(Total.AFL.CIO + 1))", sep = ""))

        if(include.factory == FALSE){
          fmla <- formula(paste(rc.tmp, " ~ dwnom1 + I(log(Total.Ford + Total.DaimlerChrysler+ Total.GM+1)) + I(log(Total.AFL.CIO + 1))", sep = ""))
        }
        
        reg.out <- glm(fmla, family = binomial(link = "logit"), data = vote.data)
        
        coefs <- coef(summary(reg.out))[, 1]
        #        if(length(coefs) < length(2:ncol(storage))){
        #          coefs <- append(NA, coefs)
        #        }
        if(is.na(storage[1, "vote"])){
          storage[1, ] <- c(rc.tmp, coefs)
        }else{
          storage <- rbind(storage, c(rc.tmp, coefs))
        }
      }
    }
  }
  for(j in 2:ncol(storage)){
    storage[, j] <- as.numeric(storage[, j])
  }
  return(storage)
}

## Remove duplicate district appearances for raw counts AT TIME of each of the VOTES (110.2.690 and 111.1.314).  
## Function takes vec of districts to cut, which party to cut, and vec of districts to cut 1 of (where party is same for both members).
cut.func <- function(vec.spec = NULL, vec.spec.party, vec.spec.congress, vec.spec.same = NULL, vec.spec.same.which, vec.spec.same.congress, data){
  to.cut <- NULL
  if(!is.null(vec.spec)){
    for(i in 1:length(vec.spec)){
      to.cut <- append(to.cut, row.names(data[data[,"state.abb"]==substr(vec.spec[i], 1, 2) & data[,"district"]==substr(vec.spec[i], 3, nchar(vec.spec[i])) & data[, "party"]==vec.spec.party[i] & data[, "congress"]==vec.spec.congress[i],]))
    }
  }
  if(!(is.null(vec.spec.same))){
    for(i in 1:length(vec.spec.same)){ # just cut first one.
      to.cut <- append(to.cut, row.names(data[data[,"state.abb"]==substr(vec.spec.same[i], 1, 2) & data[,"district"]==substr(vec.spec.same[i], 3, nchar(vec.spec.same[i])) & data[, "congress"]==vec.spec.same.congress[i], ])[vec.spec.same.which[i]])    
    }
  }
  return(data[!(row.names(data) %in% to.cut), ])
}
